<template>
  <div class="user-container">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-form :inline="true" :model="searchForm">
        <el-form-item>
          <el-input v-model="searchForm.nickName" placeholder="用户昵称" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>搜索
          </el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 用户列表 -->
    <el-card class="user-table-card" shadow="hover">
      <el-table 
        :data="userList" 
        border 
        style="width: 100%"
        :header-cell-style="{
          background: '#f5f7fa',
          color: '#606266',
          fontWeight: 'bold'
        }"
        :row-class-name="tableRowClassName"
      >
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="nickName" label="昵称" width="120" align="center" />
        <el-table-column prop="username" label="用户名" width="120" align="center" />
        <el-table-column prop="email" label="邮箱" width="180" align="center" />
        <el-table-column prop="phone" label="手机号" width="120" align="center" />
        <el-table-column prop="role" label="角色" width="120" align="center">
          <template #default="scope">
            <el-tag 
              :type="scope.row.role === 1 ? 'danger' : 'success'"
              effect="dark"
              size="small"
            >
              {{ scope.row.role === 1 ? '管理员' : '普通用户' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="state" label="状态" width="120" align="center">
          <template #default="scope">
            <el-tag 
              :type="scope.row.state === 1 ? 'success' : 'info'"
              effect="dark"
              size="small"
            >
              {{ scope.row.state === 1 ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="注册时间" width="180" align="center">
          <template #default="scope">
            {{ formatDateTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <el-button-group>
              <el-button 
                type="primary" 
                size="small"
                @click="handleViewDetail(scope.row)"
              >
                查看详情
              </el-button>
              <el-button 
                type="primary" 
                size="small"
                @click="handleEditRole(scope.row)"
                :disabled="isCurrentUser(scope.row.id)"
                :title="isCurrentUser(scope.row.id) ? '不能修改当前登录用户的角色' : ''"
              >
                修改角色
              </el-button>
              <el-button
                :type="scope.row.state === 1 ? 'danger' : 'success'"
                size="small"
                @click="handleToggleStatus(scope.row)"
                :disabled="isCurrentUser(scope.row.id)"
                :title="isCurrentUser(scope.row.id) ? '不能修改当前登录用户的状态' : ''"
              >
                {{ scope.row.state === 1 ? '禁用' : '启用' }}
              </el-button>
              <el-button
                type="danger"
                size="small"
                @click="handleDelete(scope.row)"
                :disabled="isCurrentUser(scope.row.id)"
                :title="isCurrentUser(scope.row.id) ? '不能删除当前登录的用户' : ''"
              >
                删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
        />
      </div>
    </el-card>

    <!-- 修改角色对话框 -->
    <el-dialog 
      v-model="roleDialog.visible" 
      title="修改用户角色" 
      width="30%"
      destroy-on-close
      center
    >
      <el-form :model="roleDialog.form" class="dialog-form">
        <el-form-item label="角色">
          <el-select v-model="roleDialog.form.role" class="dialog-select">
            <el-option label="管理员" :value="1" />
            <el-option label="普通用户" :value="0" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="roleDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="confirmEditRole">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 用户详情对话框 -->
    <el-dialog 
      v-model="detailDialog.visible" 
      title="用户详情" 
      width="50%"
      destroy-on-close
      center
    >
      <div v-if="detailDialog.data" class="user-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="用户ID">{{ detailDialog.data.id }}</el-descriptions-item>
          <el-descriptions-item label="用户名">{{ detailDialog.data.username }}</el-descriptions-item>
          <el-descriptions-item label="昵称">{{ detailDialog.data.nickName }}</el-descriptions-item>
          <el-descriptions-item label="邮箱">{{ detailDialog.data.email }}</el-descriptions-item>
          <el-descriptions-item label="手机号">{{ detailDialog.data.phone }}</el-descriptions-item>
          <el-descriptions-item label="角色">
            <el-tag :type="detailDialog.data.role === 1 ? 'danger' : 'success'">
              {{ detailDialog.data.role === 1 ? '管理员' : '普通用户' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="detailDialog.data.state === 1 ? 'success' : 'info'">
              {{ detailDialog.data.state === 1 ? '正常' : '禁用' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="注册时间">
            {{ formatDateTime(detailDialog.data.createTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="最后登录时间">
            {{ formatDateTime(detailDialog.data.lastLoginTime) }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialog.visible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { userAPI } from '@/utils/api'

// 获取当前登录用户的信息
const currentUser = ref(null)
const getCurrentUser = () => {
  try {
    const adminStr = sessionStorage.getItem('admin')
    if (adminStr) {
      currentUser.value = JSON.parse(adminStr)
      console.log('当前登录用户:', currentUser.value)
    }
  } catch (error) {
    console.error('获取当前用户信息失败:', error)
  }
}

// 搜索表单
const searchForm = reactive({
  nickName: ''
})

// 分页数据
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 用户列表数据
const userList = ref([])

// 日期格式化函数
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return '未知';
  
  try {
    const date = new Date(dateTimeStr);
    if (isNaN(date.getTime())) return dateTimeStr;
    
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  } catch (err) {
    console.error('日期格式化错误:', err);
    return dateTimeStr;
  }
};

// 获取用户列表数据
const getUserList = () => {
  console.log('获取用户列表参数:', {
    pageNum: currentPage.value,
    pageSize: pageSize.value,
    nickName: searchForm.nickName
  });
  
  const params = {
    pageNum: currentPage.value,
    pageSize: pageSize.value
  };
  
  // 如果搜索框有值，则调用搜索接口
  if (searchForm.nickName) {
    params.nickName = searchForm.nickName;
    userAPI.search(params)
      .then(handleUserResponse)
      .catch(handleUserError);
  } else {
    userAPI.getList(params)
      .then(handleUserResponse)
      .catch(handleUserError);
  }
};

// 处理用户数据响应
const handleUserResponse = (res) => {
  console.log('用户数据响应:', res);
  if (res.data.code === 200) {
    const responseData = res.data.data;
    
    // 处理不同格式的响应数据
    if (responseData.records) {
      // MyBatis Plus分页格式
      userList.value = responseData.records;
      total.value = responseData.total;
    } else if (Array.isArray(responseData)) {
      // 数组格式
      userList.value = responseData;
      total.value = responseData.length;
    } else {
      // 其他格式处理
      userList.value = [];
      total.value = 0;
      console.error('无法识别的数据格式:', responseData);
    }
  } else {
    ElMessage.error(res.data.message || '获取用户列表失败');
    userList.value = [];
    total.value = 0;
  }
};

// 处理用户数据请求错误
const handleUserError = (err) => {
  console.error('获取用户列表失败:', err);
  ElMessage.error('获取用户列表失败');
  userList.value = [];
  total.value = 0;
};

// 角色修改对话框
const roleDialog = reactive({
  visible: false,
  form: {
    id: null,
    role: 0
  }
})

// 用户详情对话框
const detailDialog = reactive({
  visible: false,
  data: null
})

// 表格行样式
const tableRowClassName = ({ row, rowIndex }) => {
  if (isCurrentUser(row.id)) {
    return 'current-user-row';
  }
  return rowIndex % 2 === 0 ? 'even-row' : 'odd-row';
}

// 检查是否为当前登录用户
const isCurrentUser = (userId) => {
  return currentUser.value && currentUser.value.id === userId
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  getUserList()
}

const resetSearch = () => {
  searchForm.nickName = ''
  currentPage.value = 1
  getUserList()
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  getUserList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  getUserList()
}

// 查看用户详情
const handleViewDetail = (row) => {
  userAPI.getDetail(row.id)
    .then(res => {
      console.log('用户详情响应:', res);
      if (res.data.code === 200) {
        detailDialog.data = res.data.data;
        detailDialog.visible = true;
      } else {
        ElMessage.error(res.data.message || '获取用户详情失败');
      }
    })
    .catch(err => {
      console.error('获取用户详情失败:', err);
      ElMessage.error('获取用户详情失败');
    });
};

// 修改角色
const handleEditRole = (row) => {
  // 检查是否为当前登录用户
  if (isCurrentUser(row.id)) {
    ElMessage.warning('不能修改当前登录用户的角色！');
    return;
  }
  
  console.log('修改角色, 用户数据:', row);
  roleDialog.form.id = row.id;
  roleDialog.form.role = row.role;
  roleDialog.visible = true;
};

const confirmEditRole = () => {
  console.log('确认修改角色:', roleDialog.form.id, roleDialog.form.role);
  
  userAPI.updateRole(roleDialog.form.id, roleDialog.form.role)
    .then(res => {
      console.log('修改角色响应:', res);
      if (res.data.code === 200) {
        ElMessage.success('修改角色成功');
        roleDialog.visible = false;
        getUserList();
      } else {
        ElMessage.error(res.data.message || '修改角色失败');
      }
    }).catch(err => {
      console.error('修改角色失败:', err);
      ElMessage.error('修改角色失败');
    });
};

// 启用/禁用用户
const handleToggleStatus = (row) => {
  // 检查是否为当前登录用户
  if (isCurrentUser(row.id)) {
    ElMessage.warning('不能修改当前登录用户的状态！');
    return;
  }
  
  // 新的状态值：当前为1则改为0，当前为0则改为1
  const newState = row.state === 1 ? 0 : 1;
  
  ElMessageBox.confirm(
    `确定要${newState === 1 ? '启用' : '禁用'}该用户吗?`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    console.log('更新用户状态:', row.id, newState);
    
    userAPI.updateStatus(row.id, newState)
      .then(res => {
        console.log('更新状态响应:', res);
        if (res.data.code === 200) {
          ElMessage.success(`${newState === 1 ? '启用' : '禁用'}用户成功`);
          getUserList();
        } else {
          ElMessage.error(res.data.message || '操作失败');
        }
      }).catch(err => {
        console.error('更新用户状态失败:', err);
        ElMessage.error('操作失败');
      });
  }).catch(() => {
    // 用户取消操作
    console.log('用户取消了操作');
  });
};

// 删除用户
const handleDelete = (row) => {
  // 检查是否为当前登录用户
  if (isCurrentUser(row.id)) {
    ElMessage.warning('不能删除当前登录的用户！');
    return;
  }
  
  ElMessageBox.confirm(
    '此操作将永久删除该用户，是否继续?',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    console.log('删除用户:', row.id);
    
    userAPI.delete(row.id)
      .then(res => {
        console.log('删除用户响应:', res);
        if (res.data.code === 200) {
          ElMessage.success('删除用户成功');
          getUserList();
        } else {
          ElMessage.error(res.data.message || '删除失败');
        }
      }).catch(err => {
        console.error('删除用户失败:', err);
        ElMessage.error('删除失败');
      });
  }).catch(() => {
    // 用户取消操作
    console.log('用户取消了删除操作');
  });
};

onMounted(() => {
  getCurrentUser()
  getUserList()
})
</script>

<style scoped>
.user-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 84px);
}

.search-bar {
  margin-bottom: 20px;
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.user-table-card {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.even-row {
  background-color: #fafafa;
}

.odd-row {
  background-color: #ffffff;
}

.dialog-form {
  padding: 20px 40px;
}

.dialog-select,
.dialog-input {
  width: 100%;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding: 0 20px 20px;
}

.user-detail {
  padding: 20px;
}

:deep(.el-button) {
  padding: 8px 16px;
}

:deep(.el-table) {
  border-radius: 4px;
  overflow: hidden;
}

:deep(.el-table th) {
  font-size: 14px;
}

:deep(.el-dialog__header) {
  margin-right: 0;
  padding: 20px;
  border-bottom: 1px solid #dcdfe6;
}

:deep(.el-dialog__body) {
  padding: 0;
}

:deep(.el-form-item__label) {
  font-weight: bold;
}

.current-user-row {
  background-color: #e6f7ff !important;
  font-weight: bold;
}

:deep(.current-user-row td) {
  background-color: #e6f7ff !important;
}
</style>